// 选集记录存储的键名前缀
const EPISODE_HISTORY_KEY_PREFIX = 'yzzy_episode_history_';

/**
 * 保存视频选集记录到localStorage
 * @param videoId 视频ID
 * @param episodeIndex 选集索引
 */
export function saveEpisodeHistory(videoId: number, episodeIndex: number): void {
  try {
    if (typeof window === 'undefined') return;
    
    const key = `${EPISODE_HISTORY_KEY_PREFIX}${videoId}`;
    localStorage.setItem(key, episodeIndex.toString());
    
    // 记录最后访问时间，用于清理过期记录
    const timestamp = Date.now();
    localStorage.setItem(`${key}_time`, timestamp.toString());
  } catch (error) {
    console.error('保存选集记录失败:', error);
  }
}

/**
 * 获取视频选集记录
 * @param videoId 视频ID
 * @returns 选集索引，如果没有记录返回-1
 */
export function getEpisodeHistory(videoId: number): number {
  try {
    if (typeof window === 'undefined') return -1;
    
    const key = `${EPISODE_HISTORY_KEY_PREFIX}${videoId}`;
    const episodeIndex = localStorage.getItem(key);
    
    return episodeIndex ? parseInt(episodeIndex, 10) : -1;
  } catch (error) {
    console.error('获取选集记录失败:', error);
    return -1;
  }
}

/**
 * 清理过期的选集记录
 * @param maxAgeInDays 最大保留天数，默认为30天
 */
export function cleanupEpisodeHistory(maxAgeInDays: number = 30): void {
  try {
    if (typeof window === 'undefined') return;
    
    const now = Date.now();
    const maxAge = maxAgeInDays * 24 * 60 * 60 * 1000; // 转换为毫秒
    
    // 遍历localStorage清理过期记录
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (!key || !key.startsWith(EPISODE_HISTORY_KEY_PREFIX)) continue;
      
      // 跳过非时间戳记录
      if (key.endsWith('_time')) continue;
      
      // 获取时间戳记录
      const timeKey = `${key}_time`;
      const timeValue = localStorage.getItem(timeKey);
      
      if (timeValue) {
        const timestamp = parseInt(timeValue, 10);
        if (now - timestamp > maxAge) {
          // 删除过期记录
          localStorage.removeItem(key);
          localStorage.removeItem(timeKey);
        }
      }
    }
  } catch (error) {
    console.error('清理选集记录失败:', error);
  }
} 